<template>
	<view :style="bodyStyle">
		<view class="flex-col-center">
			<image class="hw128 round"  :src="logoImg" ></image>
			<view class="font-s48 margin-top-32 text-bold">
				<text class="text-purple">Ole Chat</text>
				<text class="margin-left-5">管理后台</text>
			</view>
            <view class="margin-top-32">
                <u-form labelPosition="left" ref="formRef" :model="form" :rules="formRule" :labelStyle="{width: '3000px'}">
                    <!-- 用户名 -->
                    <up-form-item prop="email" borderBottom>
                        <up-input type="text" placeholder="请输入邮箱"   :adjustPosition="false" prefixIcon="email"  :prefixIconStyle="iconStyle"	v-model="form.email" 	border="surround" ></up-input>
                    </up-form-item>
                    <!-- 验证码 -->
                    <up-form-item prop="captchaCode" borderBottom>
                        <up-input type="text" placeholder="请入邮箱验证码"    :adjustPosition="false" prefixIcon="lock"  :prefixIconStyle="iconStyle"  v-model="form.code"	border="surround">
                            <template #suffix>
                                <up-button  type="primary" :disabled="isDisabledSend "  @click="toSendCode"  size="mini">{{ codeButtomText }}</up-button>
                            </template>
                        </up-input>
                    </up-form-item>
                </u-form>
                <up-button type="success"  :loading="loading" :disabled="loading" @click="onLogin">
                    <text>登</text><text class="margin-lr-40"></text><text>入</text>
                </up-button>
            </view>
		</view>
	</view>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
import { computed  } from 'vue'
import { showError } from '@/utils/msg-show'
import { sendCaptchaApi } from '@/api/admin/login'
import { urls } from '@/security/paths'
import { switchTab } from '@/security/router'
import { useAuthStore } from "@/store"

const authStore = useAuthStore()

const windowInfo = uni.getWindowInfo()
const screenHeight = windowInfo.screenHeight

import logoImg from "@/static/logo.png"
// 正则说明：
// 1. 本地部分：允许字母、数字、_ % + - . ，且不能以 . 开头/结尾，不能有连续 .
// 2. @ 符号：必须存在且唯一
// 3. 域名部分：允许字母、数字、- ，段间用 . 分隔，顶级域名至少 2 个字符（如 .com .cn）
const emailReg = /^[a-zA-Z0-9_%+-]+(?:\.[a-zA-Z0-9_%+-]+)*@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}$/;

const iconStyle = reactive<any>({ fontSize: "22px",color: "#909399",})

const loading = ref(false)

const timeLimit = ref(600)
const timerId = ref()
const codeButtomText = ref<string>("获取邮箱验证码")
const isDisabled = ref(false)

const bodyStyle = reactive<any>({
    paddingTop: Math.floor(screenHeight * 0.1) + 'px',
    width: '100%'
}) 

const formRef = ref();
const form = reactive<any>({
  email: '',
  code: '',
})

const formRule= reactive<any>({
  "email": [
        { type: 'string', required: true, message: '邮箱不能为空',trigger: ['blur', 'change'] },
       	{ validator: (rule:any, value:string, callback:any) => {
				return emailReg.test(value.trim());
			}, message: '邮箱格式错误' ,trigger: ['blur']}, 
],
  "code": { type: 'string', required: true, message: '验证码不能为空',trigger: ['blur', 'change'] },
})

const isDisabledSend = computed(() => {
    return isDisabled.value || !(typeof form.email === 'string' && emailReg.test(form.email.trim()))
})

// 获取验证码
async function toSendCode(){
   isDisabled.value = true
   await sendCaptchaApi({email: form.email}).then(() => {
        // 获取定时器ID，以便后续清除
        timerId.value = setInterval(() => {
            timeLimit.value = timeLimit.value - 1
            codeButtomText.value = "剩余时效 " + timeLimit.value + " 秒"
            if (timeLimit.value  <= 0) {
                clearInterval(timerId.value);
                codeButtomText.value = "获取邮箱验证码"
                isDisabled.value = false
            }
        }, 1000);
   }).catch((err) => {
        showError(err.msg || err.errMsg || err)
   }).finally(()=>{
    //    isDisabled.value = false
   })
}
// 登入
async function onLogin(){
    const valid = await formRef.value.validate()
    if(!valid) return
    loading.value = true
    uni.showLoading({mask: true, title: '登入中...'});
    authStore.login(form).then( res => {
        switchTab(urls.Anchor)
    }).catch(err => {
        showError(err.msg || err.errMsg || err)
    }).finally(()=>{
        loading.value = false
        uni.hideLoading()
   })
}
</script>